<template>
  <div class="search clear">
    <div class="search-box-layout">
      <Row :gutter="24">
        <div v-for="(item, index) in columns" :key="index">
          <Col :span="item.span || span">
            <p class="label">{{ item.title }}</p>
            <div class="ipt">
              <Select
                  v-model="searchParams[item.key]"
                  v-if="item.type == 'select'"
                  filterable
                  :placeholder="item.placeholder || '请选择'"
                  clearable
                  :multiple="!!item.multiple"
              >
                <Option
                    v-for="(itemS, indexS) of item.dicData ? item.dicData : allDicData[item.key + 'List']"
                    :value="itemS[!!item.params ? item.params.value : 'value']"
                    :key="indexS"
                    :label="itemS[!!item.params ? item.params.label : 'label']"
                >
                </Option>
              </Select>
              <Select
                  v-model="searchParams[item.key]"
                  v-else-if="item.type == 'search'"
                  filterable
                  clearable
                  :remote-method="fn['get' + item.key]"
                  :placeholder="item.placeholder || '请选择'"
              >
                <Option
                    v-for="(itemS, indexS) of item.dicData ? item.dicData : allDicData[item.key + 'List']"
                    :value="itemS[!!item.params ? item.params.value : 'value']"
                    :key="indexS"
                    :label="itemS[!!item.params ? item.params.label : 'label']"
                >
                </Option>
              </Select>

              <Cascader
                  v-else-if="item.type == 'cascader'"
                  clearable
                  :data="item.dicData ? item.dicData : allDicData[item.key + 'List']"
                  v-model="searchParams[item.key]"
                  change-on-select
                  :placeholder="item.placeholder || '请选择'"
              >
              </Cascader>

              <DatePicker
                  v-else-if="
									item.type == 'date' || item.type == 'daterange' || item.type == 'month' || item.type == 'datetimerange' || item.type == 'year'
								"
                  :value="searchParams[item.key]"
                  @on-change="timeChange($event, item.key)"
                  :type="item.type"
                  :format="item.format ? item.format : 'yyyy-MM-dd'"
                  :placeholder="item.placeholder || '请选择日期'"
              />

              <RadioGroup v-model="searchParams[item.key]" v-else-if="item.type == 'radio'">
                <Radio label="">{{ $t('common.all') }}</Radio>
                <Radio label="1">{{ $t('common.Yes') }}</Radio>
                <Radio label="0">{{ $t('common.No') }}</Radio>
              </RadioGroup>

              <el-select v-else-if="item.type == 'wareStorage'" size="small" v-model="searchParams[item.key]" filterable
                         placeholder="请选择" clearable style="width:100%">
                <el-option-group
                    v-for="group in item.dicData ? item.dicData : allDicData[item.key + 'List']"
                    :key="group.value"
                    :label="group.label">
                  <el-option
                      v-for="item in group.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-option-group>
              </el-select>

              <Input
                  v-else
                  type="text"
                  clearable
                  v-model="searchParams[item.key]"
                  :placeholder="item.placeholder || '请输入'"
                  class="inputBorder"
                  :maxlength="32"
              ></Input>
            </div>
          </Col>
        </div>
        <div>
          <Col :span="otherSpan || 4">
            <div>
              <p class="label hide-label">--</p>
              <div class="ipt">
                <Button type="primary" class="search-btn" @click="changeNum()">{{ $t('common.Query') }}</Button>
                <Button class="reset-btn" @click="reset()">{{ $t('common.reset') }}</Button>
                <slot name="others"></slot>
              </div>
            </div>
          </Col>
        </div>
      </Row>
    </div>
  </div>
</template>

<script>
import recursion from '@/util/recursion';
import toggleTableOperation from '@/mixins/toggleTableOperation';

export default {
  name: 'equipmentsLedgerPageList',
  mixins: [toggleTableOperation],
  props: {
    columns: {
      type: Array,
    },
    span: {
      type: Number,
      default: 4,
    },
    otherSpan: {
      type: Number,
      default: 4,
    },
  },
  data() {
    return {
      searchParams: {},
      fn: {},
      allDicData: {},
      validateWritefunction: {
        deviceNo: [
          {
            required: true,
            message: this.$t('equipLedger.inputDeviceNo'),
            trigger: 'change',
          },
        ],
      },
    };
  },
  created() {
    // this.getFaultCategory("设备类型");
    this.columns.forEach((res) => {
      const item = res;
      if (item.dicUrl) {
        this[item.key] = [];
        if (item.type == 'select') {
          this.getDicData(item.dicUrl, item.key);
        } else if (item.type == 'cascader') {
          this.getCasDicData(item.dicUrl, item.key, item.params);
        }
      }
      if (item.type == 'search') {
        const that = this;
        this.fn['get' + item.key] = function (query) {
          let params,
              data = {};
          if (item.queryMethod == 'post') {
            data = {
              ...item.queryParams,
            };
            data[item.queryName] = query;
          } else {
            params = {
              ...item.queryParams,
            };
            params[item.queryName] = query;
          }
          that
              .axios({
                method: item.queryMethod || 'get',
                url: item.dicUrl,
                params,
                data,
              })
              .then((re) => {
                if (re.code === 200) {
                  const resStr = that.getData(item.resultParams, re) || [];
                  that.$set(that.allDicData, `${item.key}List`, item.resultParams ? resStr : re.data);
                }
              });
        };
      }
      this.initDefaultTimeParams(item);
    });
  },
  methods: {
    initDefaultTimeParams(item) {
      if (item.type == 'date' || item.type == 'daterange' || item.type == 'month' || item.type == 'datetimerange' || item.type == 'year') {
        if (item.defaultTimeRange) {
          const valueFormatter = item.format ? item.format.replace(/y/g, 'Y').replace(/d/g, 'D') : 'YYYY-MM-DD';
          const endDay = item.pushDay ? this.$moment(new Date()).subtract(-1, 'days').format(valueFormatter) : this.$moment(new Date()).format(valueFormatter);
          const defaultTimeRangeList = [
            this.$moment(new Date()).subtract(item.defaultTimeRange, 'days').format(valueFormatter),
            endDay,
          ];
          // this.$set(this.columns[index], 'defaultTimeRangeList', defaultTimeRangeList);
          this.$set(this.searchParams, item.key, defaultTimeRangeList);
        }
      }
    },
    timeChange(val, key) {
      if (Array.isArray(val) && !val[0]) {
        delete this.searchParams[key]
      } else this.$set(this.searchParams, key, val);

      const arg = this.columns.find((item) => item.key == key);
      if (arg && arg.cascader) {
        const obj = JSON.stringify({eqfaeqr: val}).replace('eqfaeqr', `${key}`);
        this.$set(this.cascaderParams, `${arg.cascader}CascaderParams`, JSON.parse(obj));
        const arg1 = this.columns.find((item) => item.key == arg.cascader);
        this.getDicData(arg1.dicUrl, arg1.key);
      }
    },
    getData(str, apiData) {
      const resultArray = str.split('.');
      let res = JSON.parse(JSON.stringify(apiData));
      resultArray.forEach((item, index) => {
        if (index !== 0 && item !== 'res') {
          res = res[item];
        }
      });
      return res;
    },
    getDicData(url, key) {
      this.$nextTick(() => {
        this.axios({
          method: 'get',
          url: url,
        }).then((res) => {
          this.$set(this.allDicData, `${key}List`, res.data);
        });
      });
    },
    getCasDicData(url, key, params) {
      this.$nextTick(() => {
        this.axios({
          method: 'get',
          url: url,
        }).then((res) => {
          let obj = {};
          if (params) {
            obj = params;
          } else {
            obj = {
              label: 'name',
              value: 'code',
              children: 'children',
            };
          }
          this.$set(this.allDicData, `${key}List`, recursion.convertTree(res.data, obj));
        });
      });
    },
    reset() {
      let obj = {...this.searchParams};

      this.columns.forEach((item) => {
        if (item.noreset == true) {
          this.initDefaultTimeParams(item);
        } else delete obj[item.key];
      });
      this.$set(this, 'searchParams', obj);

      this.$emit('reset');
      this.changeNum();
    },
    //分页
    changeNum() {
      this.$emit('getSearch', this.searchParams);
    },
  },
};
</script>
<style scoped lang="scss"></style>
